package com.elective.courseselect.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elective.courseselect.dao.CharacterDao;
import com.elective.courseselect.dao.StudentCharacterDao;
import com.elective.courseselect.dao.StudentDao;
import com.elective.courseselect.dao.UserDao;
import com.elective.courseselect.entity.*;
import com.elective.courseselect.enums.UserType;
import com.elective.courseselect.service.*;
import com.elective.courseselect.serviceUtils.UserUtils;
import com.elective.courseselect.utils.PageUtils;
import com.elective.courseselect.utils.Query;
import com.elective.courseselect.utils.R;
import com.elective.status.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;



@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private StudentCharacterService studentCharacterService;

    @Autowired
    private StudentCharacterDao studentCharacterDao;

    @Autowired
    private CharacterService characterService;

    @Autowired
    private CharacterDao characterDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R login(UserEntity user) {
        QueryWrapper<UserEntity> wrapper = createExample(user);
        UserEntity one = this.getOne(wrapper);
        //判断账号是否被禁用
        Boolean abandon = UserUtils.isAbandon(one.getId());
        if (abandon) {
            return R.error(StatusCode.ERROR, "该账号已被禁用");
        }else{
            return R.ok(StatusCode.OK,"登录成功");
        }
    }

    @Override
    public UserEntity userInfo(Integer id) {
        UserEntity user = this.getById(id);
        //管理员
        if (user.getRole() == UserType.SUPER_ADMIN) {

        }
        //老师
        else if (user.getRole() == UserType.TEACHER) {

        }
        //学生
        else{

        }
        return null;
    }

    @Override
    public UserEntity insertUser(UserEntity user) {
        //管理员
        if (user.getRole() == UserType.SUPER_ADMIN) {

        }
        //老师
        else if (user.getRole() == UserType.TEACHER) {

        }
        //学生
        else{
            //新增用户
            userDao.insert(user);
            Integer userId = user.getId();
            StudentEntity studentEntity = new StudentEntity();
            studentEntity.setUserId(userId);
            studentEntity.setName("请更新您的名字");
            studentDao.insert(studentEntity);
        }
        return user;
    }

    @Override
    public UserVo searchUserInfos(Integer userId) {
        //返回res
        UserVo userVo = new UserVo();

        //性格标签List
        ArrayList<String> labelList = new ArrayList<>();

        //user表数据
        UserEntity userEntity = this.getById(userId);

        //学生表数据
        StudentEntity studentEntity = new StudentEntity();
        studentEntity.setUserId(userId);
        QueryWrapper studentQuery = StudentServiceImpl.createExample(studentEntity);
        studentEntity = studentService.getOne(studentQuery);

        //学生品质表数据
        StudentCharacterEntity characterEntity = new StudentCharacterEntity();
        characterEntity.setStudentId(userId);
        QueryWrapper characterQuery = StudentCharacterServiceImpl.createExample(characterEntity);
        characterEntity = studentCharacterService.getOne(characterQuery);


        //品质表
        for (String characterId : characterEntity.getCharacterId().split(",")) {
            if ("".equals(characterId.trim())) {
                continue;
            }else{
                String label = characterService.getById(characterId).getLabel();
                labelList.add(label);
            }
        }


        userVo.setUserId(userId);
        userVo.setRole(userEntity.getRole());
        userVo.setCharacterLabel(labelList);
        userVo.setPassword("**********");
        userVo.setCharacterId(characterEntity.getCharacterId());
        userVo.setName(studentEntity.getName());

        return userVo;
    }

    @Override
    public JSONObject getMaxStuAndTeaAccount() {
        JSONObject jsonObject = new JSONObject();
        Integer stuRole = UserType.STUDENT.getCode();
        Integer teaRole = UserType.TEACHER.getCode();
        Integer adminRole = UserType.SUPER_ADMIN.getCode();
        Integer ordinaryAdmin = UserType.ORDINARY_ADMIN.getCode();
        Integer stuAccountId = userDao.getMaxAccountByRole(stuRole);
        Integer teaAccountId = userDao.getMaxAccountByRole(teaRole);
        Integer adminAccountId = userDao.getMaxAccountByRole(adminRole);
        Integer ordinaryAdminId = userDao.getMaxAccountByRole(ordinaryAdmin);
        jsonObject.put("stuMaxAccount", stuAccountId);
        jsonObject.put("teaMaxAccount", teaAccountId);
        jsonObject.put("adminMaxAccount", adminAccountId);
        jsonObject.put("ordinaryMaxAccount", ordinaryAdminId);
        return jsonObject;
    }


    public Integer getMaxAccount() {
        Integer maxAccount = userDao.getMaxAccount();
        return maxAccount;
    }

    @Override
    public R createAccount(JSONObject json) {
        Integer createRoleType = json.getInteger("role");
        UserType userType = UserType.getByCode(createRoleType);
        Integer createNumber = json.getInteger("number");
        Integer createStartId = json.getInteger("startId");
        Integer maxAccount = getMaxAccount();
        if (createStartId < maxAccount) {
            return R.error(StatusCode.ERROR, "开始ID小于数据库最大账号").put("目前最大账号是",maxAccount);
        }else{
            List<UserEntity> createUsers =new ArrayList<>();
            for (int i = 0; i < createNumber; i++) {
                UserEntity userEntity = new UserEntity();
                userEntity.setPassword("00000");
                userEntity.setRole(userType);
                userEntity.setState(0);
                createUsers.add(userEntity);
            }
            userDao.changeStartIncrementVal(createStartId);
            this.saveBatch(createUsers);

            switch (createRoleType) {
                case StatusCode.ROLE_STU:
                    List<StudentEntity> createStudent =new ArrayList<>();
                    for (UserEntity createUser : createUsers) {
                        StudentEntity studentEntity = new StudentEntity();
                        studentEntity.setName("初始化昵称"+createUser.getId());
                        studentEntity.setUserId(createUser.getId());
                        createStudent.add(studentEntity);
                    }
                    studentService.saveBatch(createStudent);
                    break;
                case StatusCode.ROLE_TEA:
                    List<TeacherEntity> createTeaList =new ArrayList<>();
                    for (UserEntity createUser : createUsers) {
                        TeacherEntity teacherEntity = new TeacherEntity();
                        teacherEntity.setName("初始化昵称"+createUser.getId());
                        teacherEntity.setUserId(createUser.getId());
                        createTeaList.add(teacherEntity);
                    }
                    teacherService.saveBatch(createTeaList);
                    break;
            }
            return R.ok(StatusCode.OK, "批量新增成功").put("list", createUsers);
        }
    }

    @Override
    public void delAccount(Integer[] userIds) {
        userDao.delBatchAccount(userIds);
    }


    /**
     * Application构建查询对象
     * @param userEntity
     * @return
     */
    public static QueryWrapper createExample(UserEntity userEntity){
        QueryWrapper<StudentEntity> wrapper = new QueryWrapper<>();
        if(userEntity!=null){
            //
            if(!StringUtils.isEmpty(userEntity.getId())){
                wrapper.eq("id",userEntity.getId());
            }
            //
            if(!StringUtils.isEmpty(userEntity.getPassword())){
                wrapper.eq("password",userEntity.getPassword());
            }
            if(!StringUtils.isEmpty(userEntity.getRole())){
                wrapper.eq("role",userEntity.getRole());
            }
        }
        return wrapper;
    }
}